package com.virus.server.servlet;

import com.virus.server.catalina.Context;
import com.virus.server.http.Request;
import com.virus.server.http.Response;
import com.virus.server.utils.ServerXmlUtils;

import javax.servlet.*;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class DynamicServlet extends GenericServlet {

    public static DynamicServlet INSTANCE = new DynamicServlet();

    private Map<String, Context> contextMap;

    private DynamicServlet(){
        contextMap = ServerXmlUtils.getContextMap();
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        Request request = (Request) servletRequest;
        Response response = (Response) servletResponse;
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        Set<String> keySet = contextMap.keySet();
        for (String key : keySet) {
            Context context = contextMap.get(key);
            if (key.equals(contextPath) && context.getServletClass(servletPath) != null) {
                try {
                    String servletClass = request.getContext().getServletClass(servletPath);
                    Class<?> aClass = request.getContext().getAppBaseClassLoader().loadClass(servletClass);
                    Servlet servlet = context.getServlet(aClass);
                    System.out.println("当前访问servlet:[" + servlet + "]");
                    servlet.service(request, response);
                    return;
                } catch (ClassNotFoundException | ServletException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
